#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include "threshold.h"



using namespace std;
using namespace cv;



Threshold::Threshold(double t){

  Mat img, Timg;
  vector<Mat> imgHSVs;
  int nRows, nCols, i, j, fcount, gray, pcount, threshold, pixelCount[256];
  string imgPath  = "../pic/1.jpg";
  string thresholdPath = "../pic/threshold.jpg";
  
  /* 读取图片（灰度） */
  img = imread(imgPath, IMREAD_GRAYSCALE);
  nRows = img.rows;
	nCols = img.cols;
  cout << "read image ok." << "  width: " << nRows << "  heigh: " << nCols << endl;
  
  /* 获取前景像素点个数 */
  fcount = int(nRows * nCols * t);
  cout << "foreground count is : " << fcount << endl;
  
  /* 遍历像素点，获取每个像素的个数 */
  memset(pixelCount, 0, sizeof(pixelCount));;
  for (i = 0; i < nRows; i++){
    for (j = 0; j < nCols; j++){
      gray = img.at<uchar>(i, j);
      pixelCount[gray] += 1;
    }
  }
  cout << "get every pixel count ok." << endl;
  
  /* 获取前景对应阈值 */
  pcount = 0;
  threshold = 0;
  for (i = 0; i < 256; i++){
    pcount += pixelCount[i];
    if(pcount > fcount){
      threshold = i;
      break;
    }
  }
  cout << "threshold value is : " << threshold << endl;
  
  /* 二值化 */
  Timg = img;
  for (i = 0; i < nRows; i++){
    for (j = 0; j < nCols; j++){
      gray = img.at<uchar>(i, j);
      Timg.at<uchar>(i, j) = (gray > threshold || gray == threshold) ? 255 : 0;
    }
  }
  cout << "do threshold ok." << endl;
  
  
  /* 保存二值化图片 */
  imwrite(thresholdPath, Timg);
  cout << "save threshold ok." << endl;
}


Threshold::~Threshold(void){
  cout << "byby ~~~ I'm jianbao" << endl;
}





